package com.huahua.graduateschoolspringboot.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.log.Log;
import com.sun.imageio.plugins.common.ImageUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;

/**
 * @author LoveHuaHua
 * @date 2023年05月15日 9:50
 * @description believe in yourself
 */
@Slf4j
public class RecognizeUtil {
    public static final String API_KEY = "i4QoPpMT1RjaRGfD1sFfsDcD";
    public static final String SECRET_KEY = "KmtyA4al5aFI1hfKKPsZOpHeuUF0noz3";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static Integer obtainPersonCount(String imgUrl) throws IOException {
        log.info("图片地址：{}",imgUrl);
        //根据地址获取图片转base64
        byte[] bytes = HttpUtil.downloadBytes(imgUrl);
        String encode = Base64.encode(bytes);
        HttpResponse image = HttpUtil.createPost("https://aip.baidubce.com/rest/2.0/image-classify/v1/body_num?access_token=" + getAccessToken())
                .form("image", "data:image/png;base64," + encode)
                .execute();
        return new JSONObject(image.body()).getInt("person_num");
    }



    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getStr("access_token");
    }


}
